<template>
  <div>
    <h2 v-if="firstView">请输入用户名搜索</h2>
    <h2 v-if="loading">loading</h2>
    <h2 v-if="!errorMsg">{{errorMsg}}</h2>
    <div class="row">
      <div class="card" v-for="(user, index) in users" :key="index">
        <a :href="user.url" target="_blank">
          <img :src="user.img_url" style='width: 100px'/>
        </a>
        <p class="card-text">{{user.name}}</p>
      </div>
    </div>
  </div>
</template>

<script>
  import PubSub from 'pubsub-js'
  import axios from 'axios'
  export default {
    name: 'Main',
    data () {
      return {// 一般对于列表的展现有四种不同状态
        firstView: true,// 无数据状态
        loading: false,
        users: [],// {url:xxx, name:xxx, img_url:xxx}
        errorMsg: ''// 错误信息
      }
    },
    mounted () {// 注册服务

      PubSub.subscribe('search', (msg, searchName) => {

        const url = `https://api.github.com/search/users?q=${searchName}`

        // 发送ajax请求，loading展现
        this.firstView = false
        this.loading = true
        this.errorMsg = ''
        this.users = []

        axios.get(url).then(response => {
          const result = response.data
          const users = result.items.map(item =>({// 使用map映射到新的map中
            url: item.html_url,
            name: item.login,
            img_url: item.avatar_url
          }))

          this.loading = false
          this.users = users

        }).catch(error => {
           console.log(error.message)
           this.errorMsg = error.message
        })

      })

    }

  }

</script>

<style scoped>
  .card {
    float: left;
    width: 33.333%;
    padding: .75rem;
    margin-bottom: 2rem;
    border: 1px solid #efefef;
    text-align: center;
  }

  .card > img {
    margin-bottom: .75rem;
    border-radius: 100px;
  }

  .card-text {
    font-size: 85%;
  }

</style>
